package core.commit.auto;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

import context.mm_constant;
import core.commit.mm_submit;
import core.commit.param_constructor.mm_auto_commit_param_constructor;
import core.query.mm_query_result;
import core.reactor.mm_reactor;
import core.reactor.mm_start;
import log.mm_logger;
import utils.mm_parse;
import utils.mm_thread;

/**
 * 自动提交
 * @author dongyazhuo
 */
public class mm_auto_submit implements mm_submit {

	private String TAG = mm_auto_submit.class.getSimpleName() + " : ";

	private mm_reactor _mm_reactor;

	private String auto_submit_result;
	private Integer ifShowPassCodeTime = null;// 订单提交等待时间

	public mm_auto_submit(mm_reactor _mm_reactor) {
		super();
		this._mm_reactor = _mm_reactor;
		TAG += _mm_reactor._mm_config.getSet().getAccount_12306().getUser() + " : ";
	}

	/**
	 * 订单预定按钮，触发
	 */
	@Override
	public void submit(HashMap<String, Object> request_parm, mm_query_result _mm_query_result) {
		boolean reserve = reserve(request_parm, _mm_query_result);
		mm_logger.w(TAG + "reserve ：" + reserve);
		if (reserve) {
			boolean queue = queue(request_parm, _mm_query_result);// 排队
			mm_logger.w(TAG + "queue ：" + queue);
			if (queue) {
				confirm(request_parm);// 确认购买!!!
			}
		}
	}

	/**
	 * 确认提交
	 * @param request_parm
	 */
	private void confirm(HashMap<String, Object> request_parm) {
		Map<String, Object> url = _mm_reactor._mm_config.getUrl_config().get("confirmSingleForQueueAsys");
		Map<String, Object> data_par = mm_auto_commit_param_constructor.submit_confirm_data_par(request_parm,
				auto_submit_result);
		HashMap<String, Object> result = (HashMap<String, Object>) _mm_reactor._mm_http_client.send(url, data_par);
		if (null != result.get("status") && null != result.get("data")) {
			HashMap<String, Object> queueData = JSON.parseObject(result.get("data").toString(), HashMap.class);
			if (null != queueData && null != queueData.get("submitStatus")
					&& mm_parse.parse_bool(queueData.get("submitStatus"))) {
				// sendQueryOrderWaitTime//排队获取订单等待信息,每隔3秒请求一次，最高请求次数为20次！
				_mm_reactor._mm_query_order_complete.sendQueryOrderWaitTime();
			} else {
				if (null != queueData.get("errMsg")) {
					mm_logger.w(TAG + "提交订单失败，" + queueData.get("errMsg"));
				} else {
					mm_logger.w(TAG + queueData);
				}
			}
		} else if (null != result.get("messages")) {
			mm_logger.w(TAG + "提交订单失败,错误信息: " + result.get("messages"));
		}
	}

	private boolean queue(HashMap<String, Object> request_parm, mm_query_result _mm_query_result) {
		Map<String, Object> url = _mm_reactor._mm_config.getUrl_config().get("getQueueCountAsync");
		Map<String, Object> data_par = mm_auto_commit_param_constructor.submit_queue_data_par(_mm_query_result);
		HashMap<String, Object> result = (HashMap<String, Object>) _mm_reactor._mm_http_client.send(url, data_par);
		if (null != result.get("status") && null != result.get("data")) {
			if (mm_parse.parse_bool(result.get("status"))) {
				HashMap<String, Object> data = JSON.parseObject(result.get("data").toString(), HashMap.class);
				if (null != data.get("countT")) {
					String[] split = data.get("ticket").toString().split(",");
					int count = 0;
					for (String string : split) {
						count += Integer.parseInt(string);
					}
					mm_logger.i(TAG + "排队成功, 当前余票还剩余: {" + count + "} 张。");
					mm_logger.i(TAG + "验证码提交安全期，等待{" + ifShowPassCodeTime + "} ms.");
					mm_thread.sleep(ifShowPassCodeTime);
					return true;
				} else {
					mm_logger.w(TAG + "排队发现未知错误{" + result + "}，将此列车 {" + _mm_query_result.train_no + "}加入小黑屋");
					int ticket_black_list_time = _mm_reactor._mm_config.getTicket_black_list_time();
					_mm_reactor._mm_cache.set(_mm_query_result.train_no, ticket_black_list_time * 60 * 1000);
				}
			}
		} else if (null != result.get("messages")) {
			mm_logger.w(TAG + "排队发现未知错误{" + result + "}，将此列车 {" + _mm_query_result.train_no + "}加入小黑屋");
			int ticket_black_list_time = _mm_reactor._mm_config.getTicket_black_list_time();
			_mm_reactor._mm_cache.set(_mm_reactor._mm_cache.train_no, ticket_black_list_time * 60 * 1000);
		} else if (null != result.get("validateMessages")) {
			mm_logger.w(TAG + "排队发现未知错误{" + result + "}");
		}
		return false;
	}

	/**
	 * 预定按钮触发
	 * @param request_parm
	 * @param _mm_query_result
	 * @return
	 */
	private boolean reserve(HashMap<String, Object> request_parm, mm_query_result _mm_query_result) {
		Map<String, Object> param = mm_auto_commit_param_constructor.submit_data_par(request_parm, _mm_query_result, _mm_reactor);
		Map<String, Object> url = _mm_reactor._mm_config.getUrl_config().get("autoSubmitOrderRequest");
		HashMap<String, Object> result = (HashMap) _mm_reactor._mm_http_client.send(url, param);
		mm_logger.i(TAG + "commit result : " + result);
		if (null != result && mm_parse.parse_bool(result.get("status")) && mm_parse.parse_num(result.get("httpstatus")) == 200D) {
			if (null != result.get("data")) {
				HashMap<String, Object> data = JSON.parseObject(result.get("data").toString(), HashMap.class);
				this.auto_submit_result = data.get("result").toString();
				// String ifShowPassCode = mm_parse.parse_str(data.get("ifShowPassCode"));
				ifShowPassCodeTime = mm_parse.parse_num(data.get("ifShowPassCodeTime")).intValue();
				mm_logger.i(TAG + "commit " + mm_constant.AUTO_SUBMIT_ORDER_REQUEST_C);
				return true;
			}
		} else {
			mm_logger.w(TAG + mm_constant.AUTO_SUBMIT_ORDER_REQUEST_F);
			if (null != result.get("messages")) {
				mm_logger.w(TAG + result.get("messages"));
				if (result.get("messages").toString().contains("未处理")) {
					mm_logger.w(TAG + " 您有未处理的订单，导致订票失败，请及时到官网进行处理。note:" + result.toString());
					mm_start.stop(_mm_reactor);
				}
			}
			if (null != result.get("validateMessages")) {
				mm_logger.w(TAG + result.get("validateMessages"));
			}
		}
		return false;
	}

}
